package com.example.secondhandspringboot.service.impl;

import com.example.secondhandspringboot.context.BaseContext;
import com.example.secondhandspringboot.domain.entity.ChatMessages;
import com.example.secondhandspringboot.domain.vo.ContactVO;
import com.example.secondhandspringboot.domain.vo.MessagesVO;
import com.example.secondhandspringboot.mapper.ChatMessagesMapper;
import com.example.secondhandspringboot.service.IChatMessagesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 周在林
 * @since 2024-05-15
 */
@Service
@RequiredArgsConstructor
public class ChatMessagesServiceImpl extends ServiceImpl<ChatMessagesMapper, ChatMessages> implements IChatMessagesService {

    private final ChatMessagesMapper chatMessagesMapper;

    /**
     * 修改未读消息为已读
     * @param currentUserId
     * @param contactUserId
     */
    @Override
    public void updateIdRead(Long currentUserId, Long contactUserId) {
        chatMessagesMapper.updateIsRead(currentUserId,contactUserId);
    }

    /**
     * 获取聊天记录
     * @param contactUserId
     * @return
     */
    @Override
    public List<MessagesVO> getMessages(Long contactUserId) {
        Long currentUserId = BaseContext.getCurrentId();
        // 获取所有聊天记录
        List<MessagesVO> messagesVOList = chatMessagesMapper.getMessages(currentUserId,contactUserId);
        for (MessagesVO messagesVO : messagesVOList) {
            // 判断是否是自己发送的消息
            if (Objects.equals(messagesVO.getSendUser(), currentUserId)){
                messagesVO.setSelf(true);
            }
        }
        return messagesVOList;
    }

    /**
     * 获取未读消息数量
     * @return
     */
    @Override
    public int getTotalNoticeNum() {
        Long currentId = BaseContext.getCurrentId();
        return chatMessagesMapper.getTotalNoticeNum(currentId);
    }
}
